import java.awt.*;
import java.io.*;

class CSlope extends CObject
{
	Anchor[] a;						// start & end points

	float kf,b;

	CSlope(int type,int subtype,int x1,int y1,int x2,int y2)
	{
		super(type,subtype);
		a = new Anchor[2];
		a[0] = new Anchor(x1,y1);
		a[1] = new Anchor(x2,y2);
		init();
	}

	void init()
	{
		kf = ((float)a[1].y - (float)a[0].y) / ((float)a[1].x - (float)a[0].x);
		b = (float)a[0].y - kf * (float)a[0].x;

		x1 = a[0].x;
		y1 = a[0].y;
		x2 = a[1].x;
		y2 = a[1].y;

		if (y1 > y2)
	    {
	    	dx = x1;
	    	x1 = x2;
	    	x2 = dx;
	    	dy = y1;
	    	y1 = y2;
	    	y2 = dy;
	    }

	    xmin = (x1 < x2) ? x1 : x2;
	    xmax = (x1 > x2) ? x1 : x2;
	    ymin = (y1 < y2) ? y1 : y2;
	    ymax = (y1 > y2) ? y1 : y2;

		dx = x2 - x1;
		dy = y2 - y1;

		k = imageIndex = 0;
		if (dx > 0)
		{
			k = 1;
			imageIndex = 1;
		}
		if (dx < 0)
		{
			k = -1;
			imageIndex = 2;
		}
	}

	boolean checkActive(int mx,int my)
	{
		active = false;
	    if ((xmin - 8 <= mx) && (xmax + 8 >= mx) && (my >= ymin) && (my <= ymax))
	    {
	        a[0].active = (a[0].y - 8 <= my) && (a[0].y + 8 >= my);
	        a[1].active = (a[1].y - 8 <= my) && (a[1].y + 8 >= my);
	    	if (dx == 0) active = true;
	    	else
	    	{
				int y = (int)(mx * kf + b);
				active = (Math.abs(y - my) <= 8);
			}
	    }
	    return active;
	}

	void draw(Graphics g)
	{
		boolean mode = (type == MainFrame.activeType);
		g.setColor(selected ? Color.red : (mode ? color : color2));
		if (blink || !active || selected)
		{
			g.drawLine(a[0].x,a[0].y,a[1].x,a[1].y);
			a[0].draw(g,mode);
			a[1].draw(g,mode);
		}
		blink = !blink;
	}

	void move(int mx,int my,int start_x,int start_y)
	{
		if (a[0].active) moveAnchor(0,mx,my);
		else
		if (a[1].active) moveAnchor(1,mx,my);
		else
		{
			a[0].move(mx - start_x,my - start_y);
			a[1].move(mx - start_x,my - start_y);
		}
		init();
	}

	void moveAnchor(int index,int mx,int my)
	{
		int dx = mx - a[1 - index].x;
		int dy = my - a[1 - index].y;
		if (Math.abs(dx) > 10)
		{
			float k = ((float)((int)(dy * 10 / dx))) / 10;
			if (k >= 0f) k = 1f;
			if (k < 0f) k = -1f;
			dy = (int)(dx * k);
	   		a[index].x = mx;
		}
		else a[index].x = a[1 - index].x;
   		a[index].y = a[1 - index].y + dy;
		init();
	}

	void write(DataOutputStream out) throws IOException
	{
		out.writeByte((byte)type);
		out.writeByte((byte)subtype);
		out.writeShort((short)a[0].x);
		out.writeShort((short)a[0].y);
		out.writeShort((short)a[1].x);
		out.writeShort((short)a[1].y);
	}

	static CObject read(DataInputStream in,int type) throws IOException
	{
		int subtype = in.readByte();
		int x1 = in.readShort();
		int y1 = in.readShort();
		int x2 = in.readShort();
		int y2 = in.readShort();
		return new CSlope(type,subtype,x1,y1,x2,y2);
	}
}                
